/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.admin.auth;

import app.Const;
import app.models.DaoKit;
import app.models.sys.AuthUsers;
import app.models.sys.MerchantBrand;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.controller.security.AppUser;
import com.github.sog.controller.security.Securitys;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.kit.encry.DigestsKit;
import com.github.sog.kit.encry.EncodeKit;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * <p>
 * 超级管理员.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-04-12 21:22
 * @since JDK 1.6
 */
public class AdminController extends BasicController {

    public static final String FORM_ATTR = "authUsers";

    /**
     * The index route.
     */
    public void index() {
        render("index.ftl");
    }


    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        Page<AuthUsers> authUsersPage = AuthUsers.dao.datatable(criterias);

        renderDataTables(authUsersPage, criterias);
    }


    public void create() {
        AuthUsers authUsers = new AuthUsers();
        setAttr(FORM_ATTR, authUsers);
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        render("item.ftl");
    }


    public void edit() {
        final int id = getParaToInt(0, 1);
        AuthUsers authUsers = AuthUsers.dao.findById(id);

        setAttr(FORM_ATTR, authUsers);
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        MerchantBrand merchantBrand = MerchantBrand.dao.findByMerchant(authUsers.getNumber(AppFunc.TABLE_PK_COLUMN).intValue());
        if (merchantBrand != null) {
            setAttr("brand", merchantBrand.getNumber("brand").intValue());
        }
        render("item.ftl");
    }


    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("authusers.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }


    public void save() {
        AuthUsers authUsers = getModel(AuthUsers.class);
        if (Strings.isNullOrEmpty(authUsers.getStr("real_name"))) {
            authUsers.set("real_name", authUsers.getStr("name"));
        }
        String password = authUsers.getStr("password");
        if (!Strings.isNullOrEmpty(password)) {
            byte[] salt = DigestsKit.generateSalt(EncodeKit.SALT_SIZE);
            authUsers.set("salt", EncodeKit.encodeHex(salt));
            byte[] hashPassword = DigestsKit.sha1(password.getBytes(), salt, EncodeKit.HASH_INTERATIONS);
            authUsers.set("password", EncodeKit.encodeHex(hashPassword));
        }
        long brand = getParaToLong("brand", 0l);

        if (DaoKit.isNew(authUsers)) {
            authUsers.set("create_time", DateProvider.DEFAULT.getCurrentDate());
            authUsers.save();
            if (brand > 0) {
                MerchantBrand merchantBrand = new MerchantBrand();
                merchantBrand.set("merchant", authUsers.getNumber(AppFunc.TABLE_PK_COLUMN));
                merchantBrand.set("brand", brand);
                merchantBrand.save();
            }
        } else {
            authUsers.update();
            if (brand > 0) {
                MerchantBrand merchantBrand = MerchantBrand.dao.findByMerchant(authUsers.getNumber(AppFunc.TABLE_PK_COLUMN).intValue());
                if (merchantBrand == null) {
                    merchantBrand = new MerchantBrand();
                    merchantBrand.set("merchant", authUsers.getNumber(AppFunc.TABLE_PK_COLUMN));
                    merchantBrand.set("brand", brand);
                    merchantBrand.save();
                } else {
                    merchantBrand.set("brand", brand);
                    merchantBrand.update();
                }
            }
        }
        redirect("/admin/auth/admin");
    }


    /**
     * 个人信息
     */
    public void detail() {
        AppUser loginMember = Securitys.getLoginMember();
        if (null != loginMember) {
            long id = loginMember.getId();
            AuthUsers authUsers = AuthUsers.dao.findById(id);
            setAttr(FORM_ATTR, authUsers);
            render("detail.ftl");
        }
    }

    public void updateDetail() {
        AuthUsers authUsers = getModel(AuthUsers.class);
        authUsers.update();
        redirect("/admin/home");
    }

    /**
     * 修改密码页面
     */
    public void uptPasswordPage() {
        render("uptPassword.ftl");
    }

    /**
     * 修改密码
     */
    public void updatePassword() {
        AppUser loginMember = Securitys.getLoginMember();
        if (null != loginMember) {
            long id = loginMember.getId();
            AuthUsers authUser = AuthUsers.dao.findById(id);
            String dbPassword = authUser.getStr("password");
            String oldPassword = getPara("oldPassword");

            byte[] salt = EncodeKit.decodeHex(authUser.getStr("salt"));
            byte[] hashPassword = DigestsKit.sha1(oldPassword.getBytes(), salt, EncodeKit.HASH_INTERATIONS);
            boolean equals = StringUtils.equals(EncodeKit.encodeHex(hashPassword), dbPassword);

            if (equals) {
                String newpwd = getPara("password");
                salt = DigestsKit.generateSalt(EncodeKit.SALT_SIZE);
                authUser.set("salt", EncodeKit.encodeHex(salt));
                hashPassword = DigestsKit.sha1(newpwd.getBytes(), salt, EncodeKit.HASH_INTERATIONS);
                authUser.set("password", EncodeKit.encodeHex(hashPassword));
                authUser.update();
                setAttr("msg", "恭喜你，密码修改成功");
                setAttr("states", true);
            } else {
                setAttr("msg", "原密码错误，请重新尝试");
                setAttr("states", false);
            }
            render("uptPassword.ftl");
        }
    }
}